package diona.model

import scala.collection.JavaConversions._
import collection.mutable.ListBuffer
import twitter4j.{Tweet, Query, TwitterFactory, Twitter}
import org.joda.time.DateTime
import diona.search.PostInfo

/**
 * User: anton
 * Date: 19.06.11 17:34
 */
object TwitterSearch
{
  def search(queryText: String): List[PostInfo] =
  {
    search(queryText, 1).map(t => {
      val link = "http://twitter.com/#!/support/status/" + t.getId
      new PostInfo(url = link, tstamp = new DateTime(t.getCreatedAt), isComment = false, snippet = Some(t.getText),
        author = Some(t.getFromUser))
    })
  }

  def search(queryText: String, page: Int): List[Tweet] =
  {
    if (queryText.trim.length == 0) {
      return Nil
    }
    val twitter: Twitter = new TwitterFactory().getInstance
    val query = new Query(queryText)
    query.setLang("ru")
    query.setRpp(100)
    query.setPage(page)
    twitter.setOAuthConsumer("TF1TyC35RVvRdI4jO29WQ", "EiqUBZQLJGI4NzKhPYBr8KQgdlEkqlxSzx4SaYh5E")
    twitter.search(query).getTweets.toList
  }

  def searchAll(queryText: String): List[Tweet] =
  {
    val result = new ListBuffer[Tweet]
    for (page <- 1 to 15) {
      val tRes = search(queryText, page);
      if (tRes.isEmpty) return result.toList
      result ++= tRes
    }
    result.toList
  }
}